package org.oos.model;

import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import org.oos.atom.elements.Link;
import org.oos.atom.elements.Text;
import org.oos.atom.entries.MultimediaEntry;

public class OosVideo extends OosMedia {

	private String videoPath;

	/**
	 * This enumeration describes the Sized that a video may come in:
	 * 
	 * <table border="1">
	 * <tr>
	 * <td>Small</td>
	 * <td>Medium</td>
	 * <td>Large</td>
	 * <td>Extra Large</td>
	 * </tr>
	 * <tr>
	 * <td>66x66</td>
	 * <td>92x92</td>
	 * <td>320x240</td>
	 * <td>640x360</td>
	 * </tr>
	 * </table>
	 * 
	 * @author pablo.gonzalez@11870.com
	 * 
	 */
	public enum VideoSize {
		SMALL("vsp", 66, 66), MEDIUM("vmp", 92, 92), LARGE("vlp", 320, 240), XLARGE(
				"vxlp", 640, 360);

		private String name;
		public int width;
		public int height;
		private Map<OosVideo, String> pathCache = new WeakHashMap<OosVideo, String>();

		private VideoSize(String smallName, int width, int height) {
			this.name = smallName;
			this.width = width;
			this.height = height;
		}

		PathFinder<OosVideo> PATH_FINDER = new PathFinder<OosVideo>() {

			@Override
			public CharSequence getPath(OosVideo video) {
				if (!pathCache.containsKey(video)) {
					String resultUrl = video.getPath().toString();
					// if it is the same size as original
					if (!resultUrl.contains(name)) {
						// check if the original is of other size and
						for (VideoSize size : values()) {
							if (resultUrl.contains(size.name)) {
								resultUrl = resultUrl.replace(size.name, name);
							}
						}
					}
					pathCache.put(video, resultUrl);
				}
				return pathCache.get(video);
			}
		};
	}

	final static Creator<OosVideo> CREATOR = new Creator<OosVideo>() {

		@Override
		public OosVideo create(MultimediaEntry entry) {
			List<Link> splashes = Link.find(entry.getLinks(), "splash");
			if (splashes.size() > 0) {
				OosVideo video = new OosVideo();
				Link splash = splashes.get(0);
				video.setPath(splash.getHref());
				Text content = entry.getContent();
				video.setVideoPath(content.getSrc());
				video.setType(content.getType());
				return video;
			} else {
				throw new RuntimeException(
						"There should be a splash screen for this video");
			}
		}
	};

	@Override
	public CharSequence getPath(MediaSize size) {
		return size.toSize(VideoSize.values()).PATH_FINDER.getPath(this);
	}

	protected void setVideoPath(String videoPath) {
		this.videoPath = videoPath;
	}

	public String getVideoPath() {
		return videoPath;
	}

}
